package com.hp.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class TestReflect07 {
    public static void main(String[] args) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
        //获取类的Class对象;
        Class<?> c1 = Class.forName("com.hp.reflect.User");

        //获取类的名字
        System.out.println(c1.getName());// 获得包名+类名
        System.out.println(c1.getSimpleName());// 获得类名
        System.out.println("==========================");
        //获得类的属性
        Field[] fields1 = c1.getFields();  //只能找到public属性;
        for (Field field : fields1) {
            System.out.println(field);
        }
        System.out.println("-------------------------");
        Field[] fields2 = c1.getDeclaredFields();    //可获取到所有属性;
        for (Field field : fields2) {
            System.out.println(field);
        }

        //获取类的指定属性
        Field name = c1.getDeclaredField("name");
        System.out.println(name);

        System.out.println("==========================");
        //获得类的方法
        Method[] methods = c1.getMethods();// 获取本类以及父类的所有public 方法;
        for (Method method : methods) {
            System.out.println(method);
        }
        System.out.println("-------------------------");
        Method[] declaredMethods = c1.getDeclaredMethods(); //获取本类所有方法
        for (Method method : declaredMethods) {
            System.out.println(method);
        }
        System.out.println("-------------------------");
        Method getName = c1.getMethod("getName", null);//获得指定的方法,需要给参数值  方法有重载
        System.out.println(getName);
        Method setName = c1.getMethod("setName", String.class);
        System.out.println(setName);
        System.out.println("-------------------------");
        Constructor<?>[] constructors = c1.getConstructors();// 获取public 构造方法
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        Constructor<?>[] declaredConstructors = c1.getDeclaredConstructors();//获取所有构造方法
        for (Constructor constructor : declaredConstructors) {
            System.out.println(constructor);
        }
        System.out.println("-------------------------");
        Constructor<?> declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);//获得指定构造器
        System.out.println(declaredConstructor);
    }
}
